﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SVC.client;
using DevExpress.XtraGrid.Views.Grid;

namespace UI.Forms
{
    public partial class ProductINStore : FormBase1
    {
        public string Billno { get; set; }
        private SVC.client.ProductIN  pro;
        private List<ProductIN_D> OldPro{get;set;}
        private int OldCount { get; set; }
        private BindingList<View_Goods_Lite> vbcs = null;
        SVC.client.View_Goods_Lite selectcombo = null;

        public ProductINStore()
        {
            InitializeComponent();
        }

        private void ProductINStore_Load(object sender, EventArgs e)
        {
            lue_opID.EditValue = my.emp_lite.EmplID;
            rise_quantity.Leave += new EventHandler(rise_quantity_Leave);
            bind();
        }

        private void bind()
        {
            brbtnReturn.Enabled = false;
            barbtnPay.Enabled = false;

            vbcs = my.bw.Product_Get("", my.ACID);
            rile_GoodCode.DataSource = vbcs;
            rile_GoodCode.NullText = "请选择入库产品";
            rile_GoodCode.DisplayMember = "GoodsName";
            rile_GoodCode.ValueMember = "GoodsCode";
            rile_GoodCode.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(rile_ComoID_EditValueChanging);

            rue_combo.DataSource = my.bw.View_Combo_lite_List("", my.ACID);
            rue_combo.DisplayMember = "ComboName";
            rue_combo.ValueMember = "ComboID";

            rue_ck.DataSource = my.bw.Warehouse_Get("", my.ACID);
            rue_ck.DisplayMember = "WarehouseName";
            rue_ck.ValueMember = "WarehouseID";

            dateEdit1.EditValue = DateTime.Now;
            BindingList<View_Emp_lite> emps = my.bw.View_Emp_lite_List("", my.ACID);
            BindingList<View_Client_lite> clients = my.bw.View_Client_lite_List(true, my.ACID);

            //经销商
            lue_Client.Properties.DataSource = clients;
            lue_Client.EditValue = null;

            //经手人
            lue_JSempid.Properties.DataSource = emps;
            lue_JSempid.EditValue = null;

            //复核人
            lue_Checkempid.Properties.DataSource = emps;
            lue_Checkempid.EditValue = null;

            lue_opID.Properties.DataSource = emps;
            var proIn = my.bw.ProductIN_ByBillno_Get(Billno, "", my.ACID);

            if (proIn != null)
            {
                pro = proIn;
                OldPro = proIn.D.ToList();
                btn_OK.Caption = "修改";
                if (pro.M != null)
                {
                    lue_Client.EditValue = pro.M.clientID;
                    lue_JSempid.EditValue = pro.M.handleID;
                    lue_Checkempid.EditValue = pro.M.auditor;
                    te_pid.Text = pro.M.billid;
                    te_pid.Enabled = false;
                    dateEdit1.Text = pro.M.billdate.ToString("yyyy-MM-dd");
                    OldCount = pro.D.Count;

                    brbtnReturn.Enabled = true;
                    barbtnPay.Enabled = true;
                }
                gridControl1.DataSource = pro.D;
               
            }
        }

        void rile_ComoID_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0)
            {
                selectcombo = vbcs.Single(p => p.GoodsCode == e.NewValue.ToString());
            }
            else
            {
                View_Goods_Lite oldcombo = vbcs.Single(p => p.GoodsCode == e.OldValue.ToString());
                View_Goods_Lite newcombo = vbcs.Single(p => p.GoodsCode == e.NewValue.ToString());
                ProductIN_D d = gridView1.GetRow(gridView1.FocusedRowHandle) as ProductIN_D;
                d.gcode = newcombo.GoodsCode;
                d.types = newcombo.Spec;
                d.unit = newcombo.Unit;
                d.unitprice = newcombo.inprice;
                d.counts = 0;
                d.amount = 0;
            }
        }

        #region gridView
        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            Point p = this.Location;
            if (this.MdiParent != null)
            {
                p.Offset(this.MdiParent.Location);
            }
            p.Offset(gridControl1.Location);
            p.Offset(e.Location);
            p.Y = p.Y + 50;
            if (e.Button == MouseButtons.Right)
            {
                popupMenu1.ShowPopup(p);
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (true)
            {

            }
            if (e.FocusedRowHandle >= 0)
            {
                ProductIN_D d = gridView1.GetRow(e.FocusedRowHandle) as ProductIN_D;
                //if (!string.IsNullOrWhiteSpace(d.phone))
                //{
                    //btn_WH.Enabled = true;
                //}
            }
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;

            view.ClearColumnErrors();
            //var gcode = view.GetRowCellValue(e.RowHandle, "gcode");
            //if (gcode !=null && string.IsNullOrEmpty(gcode.ToString()))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["gcode"], "请选择入库产品");
            //}
            //var types = view.GetRowCellValue(e.RowHandle, "types");
            //if (types != null && string.IsNullOrEmpty(types.ToString()))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["types"], "产品规格型号不能为空");
            //}
            //var storage = view.GetRowCellValue(e.RowHandle, "storage");
            //if (storage != null && string.IsNullOrEmpty(storage.ToString()))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["storage"], "请选择入库仓库");
            //}
            //var unit = view.GetRowCellValue(e.RowHandle, "unit");
            //if (unit != null && string.IsNullOrEmpty(unit.ToString()))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["unit"], "产品单位不能为空");
            //}
            //decimal num = 0;
            //var cot = view.GetRowCellValue(e.RowHandle, "counts");
            //decimal counts = cot != null && decimal.TryParse(cot.ToString(), out num) ? decimal.Parse(cot.ToString()) : 0;
            //if (counts<=0)
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["counts"], "请输入入库数量");
            //}

            //var uprice=view.GetRowCellValue(e.RowHandle, "unitprice");
            //decimal unitprice = uprice != null && decimal.TryParse(uprice.ToString(), out num) ? decimal.Parse(uprice.ToString()) : 0;
            //if (unitprice <= 0)
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["unitprice"], "请输入产品单价");
            //}

            //var am = view.GetRowCellValue(e.RowHandle, "amount");
            //decimal amount = uprice != null && decimal.TryParse(am.ToString(), out num) ? decimal.Parse(am.ToString()) : 0; 
            //if (amount <= 0)
            //{
            //    e.Valid = false;
            //    view.SetColumnError(view.Columns["amount"], "请输入入库总价");
            //}
        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (selectcombo != null)
            {
                gridView1.SetFocusedRowCellValue("gcode", selectcombo.GoodsCode);
                gridView1.SetFocusedRowCellValue("types", selectcombo.Spec);
                gridView1.SetFocusedRowCellValue("unit", selectcombo.Unit);
                gridView1.SetFocusedRowCellValue("counts", 0);
                gridView1.SetFocusedRowCellValue("disprice",0);
                gridView1.SetFocusedRowCellValue("discount", 0);
                gridView1.SetFocusedRowCellValue("unitprice", selectcombo.inprice);
                gridView1.SetFocusedRowCellValue("amount", 0);
                selectcombo = null;

            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                gridView1.FocusedRowHandle = e.RowHandle;
            }
        }

        #endregion

        #region 改变行位置
        private void gridView1_Layout(object sender, EventArgs e)
        {
            //updateLayout = true;

            SetPosition();
            //updateLayout = false;
        }
        private void SetPosition()
        {
            if (gridView1.OptionsView.NewItemRowPosition == NewItemRowPosition.Bottom && gridView1.SortInfo.GroupCount == 0)
            {
                gridView1.FocusedRowHandle = gridView1.RowCount - 2; ;
                gridView1.MakeRowVisible(gridView1.FocusedRowHandle, false);
            }
        }
        #endregion

        #region ***数 量***
        void rise_quantity_Leave(object sender, EventArgs e)
        {
            ProductIN_D d = gridView1.GetRow(gridView1.FocusedRowHandle) as ProductIN_D;
            if (d != null)
            {
                string newvalue = "";
                if (gridView1.EditingValue != null)
                {
                    newvalue = gridView1.EditingValue.ToString();
                }
                else
                {
                    var counts = gridView1.GetFocusedRowCellValue("counts");
                    newvalue = counts != null ? counts.ToString() : "0";
                }
                d.counts = int.Parse(newvalue);
                d.amount = d.unitprice * d.counts;
            }
        }
        #endregion

        /// <summary>
        /// 保存产品入库信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OK_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dxValidationProvider1.Validate())
            {
                if (pro.D.Count > 0)
                {
                    pro.M.balance = decimal.Parse(gridColumn8.SummaryItem.SummaryValue.ToString());
                    if (lue_Checkempid.EditValue != null)
                    {
                        pro.M.auditor = new Guid(lue_Checkempid.EditValue.ToString());
                    }
                    if (lue_JSempid.EditValue != null)
                    {
                        pro.M.handleID = new Guid(lue_JSempid.EditValue.ToString());
                    }
                    pro.M.clientID = new Guid(lue_Client.EditValue.ToString());
                    pro.M.ischeck = false;
                    pro.M.opID = my.emp_lite.EmplID;
                    pro.M.billdate = dateEdit1.DateTime;
                    pro.M.billid = te_pid.Text.Trim();
                    pro.M.Remarks = "";
                    pro.M.billnoTypes = 1;
                    pro.M.total = decimal.Parse(gridColumn8.SummaryItem.SummaryValue.ToString());

                    if (pro.D.Count > OldPro.Count)
                    {
                        for (int i = 0; i < pro.D.Count; i++)
                        {
                            if (!OldPro.Contains(pro.D[i]))
                            {
                                pro.D[i].billid = te_pid.Text.Trim();
                                my.bw.ProductIN_D_Add(pro.D[i], my.ACID);
                                pro.D.Remove(pro.D[i]);
                            }
                        }
                    }

                    string r = string.IsNullOrEmpty(Billno) ? my.bw.ProductIN_Add(pro, my.ACID) :
                        my.bw.ProductIN_Update(pro, my.ACID);
                    
                    if (string.IsNullOrEmpty(r))
                    {
                        bind();
                        Comm.ShowInfo(string.Format("单据{0}成功！", btn_OK.Caption));
                    }
                    else
                    {
                        Comm.ShowErorr(r);
                    }
                }
                else
                {
                    Comm.ShowErorr("明细不能为空！");
                }
            }
        }
        /// <summary>
        /// 转入退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void brbtnReturn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ProductINReturn pro = new ProductINReturn();
            pro.MdiParent = my.mainform;
            pro.Billno = Billno;
            pro.Show();
        }
        /// <summary>
        /// 转入收款单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barbtnPay_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (string.IsNullOrEmpty(Billno))
            {
                ProductINReturn pro = new ProductINReturn();
                pro.MdiParent = my.mainform;
                pro.Billno = Billno;
                pro.Show();
            }
        }

    }
}
